<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input placeholder="选品名称" v-model="searchInfo.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="二级类目">
          <el-select clearable placeholder="二级类目" v-model="searchInfo.categorySecond">
            <el-option :key="item" :label="item" :value="item" v-for="item in categorySearchInfo"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select clearable placeholder="状态" v-model="searchInfo.goodsOrderState">
            <el-option :key="item.label" :label="item.label" :value="item.label" v-for="item in goodsOrderStateList"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="操作人">
          <el-select clearable placeholder="操作人" v-model="searchInfo.goodsOrderOwner">
            <el-option :key="item.label" :label="`${item.label}(${item.value})`" :value="item.value" v-for="item in userOptions"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="onSubmit" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary" icon="el-icon-plus">新增进货单</el-button>
        </el-form-item>
        <el-form-item>
          <el-popover placement="top" v-model="deleteVisible" width="160">
            <p>确定要删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
              </div>
            <el-button icon="el-icon-delete" slot="reference" type="danger">批量删除</el-button>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-button @click="hidePicture" type="primary" icon="el-icon-refresh">{{hide_pic_content}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      ref="multipleTable"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :default-sort = "{prop: 'selectGoodsId', order: 'descending'}"
    >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column label="日期" width="100">
         <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
    </el-table-column>
    
    <el-table-column label="商品ID" prop="selectGoodsId" width="80"></el-table-column> 
    
    <el-table-column label="商品名称" prop="goodsName" width="200"></el-table-column> 
    
    <!-- <el-table-column label="一级类目" prop="categoryFirst" width="80"></el-table-column>  -->
    
    <el-table-column label="二级类目" prop="categorySecond" width="80"></el-table-column> 
    
    <el-table-column label="图片" prop="imageUrl" width="130">
      <template width="120" slot-scope="scope">
        <img style="width:120px;height:120px;border:none;" :src="scope.row.imageUrl" v-show="isShow" >
      </template>  
    </el-table-column> 
    
    <el-table-column label="供应商" prop="supplier" width="70">
      <template  slot-scope="scope">
        <el-button type="success" size="mini" @click="linkRow(scope.row)">跳转</el-button>
      </template>  
    </el-table-column> 
    
    <el-table-column label="进价" prop="purchasePrice" width="80"></el-table-column> 
    
    <!-- <el-table-column label="预售价" prop="preSalePrice" width="80"></el-table-column>  -->
    
    <el-table-column label="进货量" prop="goodsCount" width="80"></el-table-column> 
    
    <el-table-column label="状态" prop="goodsOrderState" width="80">
      <template slot-scope="scope">
          <div>
            <el-tag :key="scope.row.methodFiletr" :type="scope.row.goodsOrderState|tagTypeFiletr" effect="dark" size="mini">{{scope.row.goodsOrderState}}</el-tag>
          </div>
        </template>
    </el-table-column> 
    
    <!-- <el-table-column label="物流" prop="logistics" width="80"></el-table-column> -->

    <!-- <el-table-column label="操作人" prop="goodsOrderOwner" width="120"></el-table-column>  -->
    
    <!-- <el-table-column label="关联选品" prop="goodsRelateSelectId" width="120"></el-table-column>  -->
    
      <!-- <el-table-column label="操作" width="200" fixed="right" > -->
        <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button class="table-button" @click="updateGoodsOrder(scope.row)" size="small" type="primary" >编辑</el-button>
          <el-button class="table-button" @click="setStorage(scope.row)" size="small" type="primary" >入库</el-button>
          <el-button type="danger" size="mini" @click="checkLogistics(scope.row)">查物流</el-button>
          <el-button type="success" size="mini" @click="createBill(scope.row)">生成财务单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="新增进货单">
      <el-form :model="formData" label-position="right" label-width="80px">
         <el-form-item label="商品名称:">
            <el-input v-model="formData.goodsName" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
      <el-row>
        <el-col :span="8">
          <el-form-item label="一级类目" prop="feature_dimension">
            <el-select v-model="formData.categoryFirst" placeholder="请选择" size="medium" @change="handleChange">
              <el-option :key="item" :label="item" :value="item" v-for="item in categoryFirstInit"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="margin-left: 50px;">
          <el-form-item label="二级类目" prop="feature_type">
            <el-select v-model="formData.categorySecond" placeholder="请选择" size="medium">
              <el-option :key="item" :label="item" :value="item" v-for="item in categorySecondInit"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
       
      <el-form-item label="图片">
            <el-input v-model="formData.imageUrl" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
      <el-form-item label="供应商">
            <el-input v-model="formData.supplier" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
      <el-form-item label="进价">
          <el-input-number v-model="formData.purchasePrice" :precision="2" clearable></el-input-number>
      </el-form-item>
       
      <el-form-item label="预售价">
              <el-input-number v-model="formData.preSalePrice" :precision="2" clearable></el-input-number>
       </el-form-item>
       
         <el-form-item label="进货量"><el-input v-model.number="formData.goodsCount" clearable placeholder="请输入"></el-input>
      </el-form-item>
       
         <el-form-item label="物流单">
            <el-col span="5">
              <el-select v-model="formData.deliveryOperator" placeholder="请选择承运商" size="medium" @change="handleChange" clearable>
                <el-option :key="item" :label="item" :value="item" v-for="item in deliveryList"></el-option>
              </el-select>
            </el-col>
            <el-col span="8"><el-input v-model="formData.logistics" clearable placeholder="物流单号" @input="changeLogistics"></el-input></el-col>
            <el-col span="5"><el-input-number v-model="formData.deliveryAmount" clearable placeholder="物流费用"></el-input-number></el-col>
            <!-- <el-col span="3" style="margin-left:10px"><el-button type="primary" @click="createBill" :disabled="createBillBool" @mouseenter.native='btn1_show'>生成财务单</el-button></el-col> -->
      </el-form-item>
       
      <el-form-item label="关联选品">
        <el-select v-model="formData.goodsRelateSelectId" placeholder="请选择" size="medium">
          <el-option :key="item" :label="`${item.label}(${item.id})`" :value="item.id" v-for="item in selectGoodsList"></el-option>
        </el-select>
      </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="enterDialog">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
       </el-form>
      <div class="dialog-footer" slot="footer">
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
    createGoodsOrder,
    deleteGoodsOrder,
    deleteGoodsOrderByIds,
    updateGoodsOrder,
    findGoodsOrder,
    getGoodsOrderList,
    getGoodsOrderById,
    createRelateBill,
    setStateStorage
} from "@/api/goodsOrder";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import {getUserList} from "@/api/user";
import {getSelectResearchList} from "@/api/selectResearch";
import {getSelectListList} from "@/api/selectList";  //  此处请自行替换地址
// import {
//     createBillList,
//     deleteBillList,
//     deleteBillListByIds,
//     updateBillList,
//     findBillList,
//     getBillListList,
//     confirmBill
// } from "@/api/billList"; 
const goodsOrderStateList = [
  {
    value: "success",
    label: "已入库",
    type: "success"
  },
  {
    value: "failue",
    label: "运送中",
    type: "danger"
  },
  {
    value: "ready",
    label: "待下单",
    type: "warning"
  }
];
export default {
  name: "GoodsOrder",
  mixins: [infoList],
  data() {
    return {
      listApi: getGoodsOrderList,
      dialogFormVisible: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      formData: {
            selectGoodsId:0,
            goodsName:"",
            categoryFirst:"",
            categorySecond:"",
            imageUrl:"",
            supplier:"",
            purchasePrice:0,
            preSalePrice:0,
            goodsCount:0,
            logistics:"",
            goodsOrderOwner:"",
            goodsRelateSelectId:0,
            deliveryOperator: "",
            deliveryAmount: 0
      },
      userOptions:[],
      categoryFirstInit: [],
      categorySecondInit: [],
      categorySearchInfo: [],
      categoryMap: new Map(),
      selectGoodsList: [],
      goodsOrderStateList: goodsOrderStateList,
      createBillBool: true,
      deliveryList:["申通", "韵达", "邮政"],
      isShow: false,
      hide_pic_content: '显示图片'
    };
  },
  filters: {
    methodFiletr(value) {
      const target = goodsOrderStateList.filter(item => item.value === value)[0];
      return target && `${target.label}`;
    },
    tagTypeFiletr(value) {
      const target = goodsOrderStateList.filter(item => item.label === value)[0];
      return target && `${target.type}`;
    },
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd");
      } else {
        return "";
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? "是" :"否";
      } else {
        return "";
      }
    }
  },
  methods: {
      //条件搜索前端看此方法
      onSubmit() {
        this.page = 1
        this.pageSize = 10                
        this.getTableData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      deleteRow(row){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.deleteGoodsOrder(row);
        });
      },
      async onDelete() {
        const ids = []
        if(this.multipleSelection.length == 0){
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        this.multipleSelection &&
          this.multipleSelection.map(item => {
            ids.push(item.ID)
          })
        const res = await deleteGoodsOrderByIds({ ids })
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          if (this.tableData.length == ids.length) {
              this.page--;
          }
          this.deleteVisible = false
          this.getTableData()
        }
      },
    async updateGoodsOrder(row) {
      const res = await findGoodsOrder({ ID: row.ID });
      this.type = "update";
      if (res.code == 0) {
        this.formData = res.data.regoodsOrder;
        this.dialogFormVisible = true;
      }
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.formData = {
          selectGoodsId:0,
          goodsName:"",
          categoryFirst:"",
          categorySecond:"",
          imageUrl:"",
          supplier:"",
          purchasePrice:0,
          preSalePrice:0,
          goodsCount:0,
          logistics:"",
          goodsOrderOwner:"",
          goodsRelateSelectId:0,
          deliveryOperator: "",
          deliveryAmount: 0
      };
    },
    async deleteGoodsOrder(row) {
      const res = await deleteGoodsOrder({ ID: row.ID });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        if (this.tableData.length == 1) {
            this.page--;
        }
        this.getTableData();
      }
    },
    async enterDialog() {
      let res;
      switch (this.type) {
        case "create":
          res = await createGoodsOrder(this.formData);
          break;
        case "update":
          res = await updateGoodsOrder(this.formData);
          break;
        default:
          res = await createGoodsOrder(this.formData);
          break;
      }
      if (res.code == 0) {
        this.$message({
          type:"success",
          message:"创建/更改成功"
        })
        this.closeDialog();
        this.getTableData();
      }
    },
    openDialog() {
      this.type = "create";
      this.dialogFormVisible = true;
    },
    async initUserList(){
      const res =  await getUserList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.userOptions.push({
            "label": element.nickName,
            "value": element.userName
          })
        });
      }
    },
    async initCategoryList(){
      const res =  await getSelectResearchList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.categorySearchInfo.push(element.categorySecond);
          if(this.categoryMap.has(element.categoryFirst)){
            const tmp2 = this.categoryMap.get(element.categoryFirst)
            tmp2.push(element.categorySecond)
            this.categoryMap.set(element.categoryFirst, tmp2)
          }else{
            const tmp1 = [element.categorySecond]
            this.categoryMap.set(element.categoryFirst, tmp1)
          }

          // 初始化一级类目
          this.categoryFirstInit = [...this.categoryMap.keys()]
        });
      }
    },
    async handleChange(){
      this.formData.categorySecond = ""    // 清空二级级联选项
      if(this.formData.categoryFirst != ""){
        this.categorySecondInit = this.categoryMap.get(this.formData.categoryFirst)
      }
    },
    async initSelectGoodsList(){
      const res =  await getSelectListList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.selectGoodsList.push({
            "label": element.selectGoodsName,
            "id": element.selectGoodsId
          });
        });
      }
    },
    async changeLogistics(){
      if(this.formData.logistics == ""){
        this.createBillBool = true
      }else{
        this.createBillBool = false
      }
    },
    createBill(row){
      if(row.logistics == ""){
        this.$message({
          type: "warning",
          message: "请先更新物流信息，并填写物流运费"
        })
        return
      }
      this.$confirm('是否继续生成财务单?', '谨慎操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.createBillYes(row);
      });
    },
    async createBillYes(row){
      const res1 = await findGoodsOrder({ ID: row.ID });
      if (res1.code == 0) {
        if(res1.data.regoodsOrder.goodsRelateBill != ""){
          this.$message({
              type: "warning",
              message: "该财务单已存在，请勿重复生成"
          })
          return
        }else{
          const res = await createRelateBill({ goodsOrderId: row.selectGoodsId });
          if(res.code == 0){
            this.$message({
              type:"success",
              message:"创建财务单成功"
            })
            this.getTableData(); 
          }
        }
      }
    },
    async linkRow(row){
      window.open(row.supplier);
    },
    async checkLogistics(row){
      if(row.logistics == ""){
        this.$message({
          type: "error",
          message: "还未录入物流单号，无法查询"
        })
      }else{
        this.$message({
          type: "error",
          message: "还未录入物流单号，无法查询"
        })
      }
    },
    btn1_show(){
      if(this.formData.goodsRelateBill != ""){
        this.$message({
          duration: 1200,
          type: "error",
          message: "已关联财务单，禁止重复生成"
        })
        this.createBillBool = true
      }
    },
    async hidePicture(){
      if(this.isShow == false){
        this.isShow = true
        this.hide_pic_content = '隐藏图片'
      }else{
        this.isShow = false
        this.hide_pic_content = '显示图片'
        
      }
    },
    setStorage(row){
      if(row.goodsOrderState == "已入库"){
        this.$message({
          type: "info",
          message: "商品已入库，无需重新操作"
        })
        return
      }
      if(row.goodsOrderState == "待下单"){
        this.$message({
          type: "info",
          message: "商品还未下单，无法执行入库操作"
        })
        return
      }
      this.$confirm('是否确认商品已收货入库?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.setStorageConfirm(row)
      });
    },
    async setStorageConfirm(row){
      const res = await setStateStorage({ goodsOrderId: row.selectGoodsId });
      if(res.code == 0){
        this.$message({
          type:"success",
          message:"入库成功"
        })
        this.getTableData();    
      }
    }
  },
  created() {
    this.initSelectGoodsList();
    this.initCategoryList()
    this.initUserList();
    this.getTableData();  
}
};
</script>

<style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .el-tag--mini {
    margin-left: 5px;
  }
  .warning {
    color: #dc143c;
  }
</style>
<style>
  .el-select .el-input {
    width: 170px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
  .admin-box .el-input__inner {
    height: 35px;
    line-height: 30px;
  }
</style>